package com.snails.net.restful.task;

import android.content.Context;
import android.os.AsyncTask;
import android.text.TextUtils;

import com.snails.net.restful.callback.ICompleted;
import com.snails.net.restful.callback.IError;
import com.snails.net.restful.callback.ISucceed;
import com.snails.net.utils.FileUtil;

import java.io.File;

import okhttp3.ResponseBody;

/**
 * 保存下载文件任务
 * @author lawrence
 * @date 2019-04-12 17:30
 */
final public class SaveFileTask extends AsyncTask<Object, Void, File> {
    private Context ctx = null;
    private ISucceed succeed = null;
    private IError error = null;
    private ICompleted completed = null;

    public SaveFileTask(Context ctx, ISucceed succeed, IError error, ICompleted completed) {
        this.succeed = succeed;
        this.error = error;
        this.completed = completed;
        this.ctx = ctx.getApplicationContext();
    }


    @Override
    protected File doInBackground(Object... params) {
        final String downloadDir = (String) params[0];
        final String downloadFile = (String) params[1];
        final ResponseBody body = (ResponseBody) params[2];

        return FileUtil.writeToDisk(body.byteStream(), this.ctx,
                TextUtils.isEmpty(downloadDir) ? "down_loads" : downloadDir, downloadFile);
    }

    @Override
    protected void onPostExecute(File file) {
        super.onPostExecute(file);
        try{
            if (file != null) {
                if (succeed != null) { succeed.onSucceed(file.getPath()); }
            } else {
                if (error != null) { error.onError(-10000, "本地文件写入失败。"); }
            }
        } finally {
            if (completed != null) { completed.onCompleted(); }
        }
    }

}
